﻿using Calligraphy.CalligraphyData;
using Calligraphy.DataModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Windows.Devices.Input;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Input;
using Windows.UI.Input.Inking;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Automation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Shapes;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace Calligraphy
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class CustomRubbingPhoto : Calligraphy.Common.LayoutAwarePage
    {
       
        public CustomRubbingPhoto()
        {
            this.InitializeComponent();
            Erase.IsEnabled = false;
            Touch.IsEnabled = false;
            Clear.IsEnabled = false;
        }
        InkManager _inkManager = new Windows.UI.Input.Inking.InkManager();
        Point _previousContactPt;
        uint _penID;
        uint _touchID;
        private string _CurrentMode = "Ink";
        private Color _CurrentDrawingColor = Colors.Red;
        private double _CurrentDrawingSize = 4;
        double opacity = 0.4;

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            double width = Window.Current.Bounds.Width;
            double height = Window.Current.Bounds.Height;
            ScreanHeiglhtAndWidth shw = new ScreanHeiglhtAndWidth();
            shw.Height = height;
            shw.Width = width;
            ObservableCollection<object> a = new ObservableCollection<object>();
            a.Add(shw);
            this.DefaultViewModel["HeightAndWidth"] = a;
            if (navigationParameter is T_RubbingPhoto)
            {
                T_RubbingPhoto rubbingPhoto = (T_RubbingPhoto)navigationParameter;
                //if (rubbingPhoto.T_Rubbing.T_RubbingPhoto.Count == 0)
                //{
                //    RubbingPhotoesDataSource rpds = new RubbingPhotoesDataSource();
                //    rpds.LoadRubbingPhotoes(rubbingPhoto.T_Rubbing);
                //}
                this.DefaultViewModel["Items"] = rubbingPhoto.T_Rubbing.T_RubbingPhoto;
                pageTitle.Text = rubbingPhoto.T_Rubbing.T_StelePaper.Name.Trim() + " " + rubbingPhoto.T_Rubbing.Name.Trim();
            }
            else
            {
                T_PaperPhoto paperPhoto = (T_PaperPhoto)navigationParameter;
                //if (paperPhoto.T_StelePaper.T_PaperPhoto.Count == 0)
                //{
                //    PaperPhotoesDataSource.LoadPaperPhotoesByPaperPhoto(paperPhoto);
                //}
                this.DefaultViewModel["Items"] = paperPhoto.T_StelePaper.T_PaperPhoto;
                pageTitle.Text = paperPhoto.T_StelePaper.Name.Trim();
            }
            this.flipView.SelectedItem = navigationParameter;
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }
        private void ShowMessage_Click(object sender, RoutedEventArgs e)
        {
            if (this.myCanvasStretch.Visibility == Visibility.Collapsed)
            {
                this.myCanvasStretch.Visibility = Visibility.Visible;
               
            }
            else
            {
                this.myCanvasStretch.Visibility = Visibility.Collapsed;
                
            }
        }
        private void start(object sender, ManipulationStartedRoutedEventArgs e)
        {
            e.Handled = true;
        }

        private void delta(object sender, ManipulationDeltaRoutedEventArgs e)
        {
            Canvas canvas = sender as Canvas;
            this.translatetransform.X += e.Delta.Translation.X;          
            this.translatetransform.Y += e.Delta.Translation.Y;
        }

        private void complete(object sender, ManipulationCompletedRoutedEventArgs e)
        {
            e.Handled = true;
        }
          

        private void titlestatus(object sender, PointerRoutedEventArgs e)
        {
            storyboard.Stop();
            storyboard.Begin();
        }

        private void pres(object sender, PointerRoutedEventArgs e)
        {
            storyboard.Stop();
            storyboard.Begin();
        }

        private void onDragDelta_1(object sender, DragDeltaEventArgs e)
        {
            Thickness margin = myCanvasStretch.Margin;
            double yadjust = myCanvasStretch.Height + e.VerticalChange;
            double xadjust = myCanvasStretch.Width + e.HorizontalChange;
            if ((xadjust >= 0) && (yadjust >= 0))
            {
                myCanvasStretch.Width = xadjust;
                myCanvasStretch.Height = yadjust;
                myCanvasStretch.Margin = new Thickness(margin.Left, margin.Top, margin.Right - e.HorizontalChange, margin.Bottom - e.VerticalChange);
            }
        }
        
        private void onDragDelta_2(object sender, DragDeltaEventArgs e)
        {
            Thickness margin = myCanvasStretch.Margin;
            double yadjust = myCanvasStretch.Height - e.VerticalChange;
            double xadjust = myCanvasStretch.Width - e.HorizontalChange;
            if ((xadjust >= 0) && (yadjust >= 0))
            {
                myCanvasStretch.Width = xadjust;
                myCanvasStretch.Height = yadjust;
                myCanvasStretch.Margin = new Thickness(margin.Left + e.HorizontalChange, margin.Top + e.VerticalChange, margin.Right, margin.Bottom);
            }
        }
        private void onDragDelta_3(object sender, DragDeltaEventArgs e)
        {
            Thickness margin = myCanvasStretch.Margin;
            double yadjust = myCanvasStretch.Height + e.VerticalChange;
            double xadjust = myCanvasStretch.Width - e.HorizontalChange;
            if ((xadjust >= 0) && (yadjust >= 0))
            {
                myCanvasStretch.Width = xadjust;
                myCanvasStretch.Height = yadjust;
                myCanvasStretch.Margin = new Thickness(margin.Left + e.HorizontalChange, margin.Top, margin.Right, margin.Bottom - e.VerticalChange);
            }
        }
        private void onDragDelta_4(object sender, DragDeltaEventArgs e)
        {
            Thickness margin = myCanvasStretch.Margin;
            double yadjust = myCanvasStretch.Height - e.VerticalChange;
            double xadjust = myCanvasStretch.Width + e.HorizontalChange;
            if ((xadjust >= 0) && (yadjust >= 0))
            {
                myCanvasStretch.Width = xadjust;
                myCanvasStretch.Height = yadjust;
                myCanvasStretch.Margin = new Thickness(margin.Left, margin.Top, margin.Right - e.HorizontalChange, margin.Bottom - e.VerticalChange);
            }
        }

        private void inertiastart(object sender, ManipulationInertiaStartingRoutedEventArgs e)
        {
            e.TranslationBehavior.DesiredDeceleration = 10;
        }

        private void changed(object sender, SelectionChangedEventArgs e)
        {
            
            storyboard.Stop();
            storyboard.Begin();
        }

        private void InkCanvas_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            PointerPoint pt = e.GetCurrentPoint(InkCanvas);         
            _previousContactPt = pt.Position;
            PointerDeviceType pointerDevType = e.Pointer.PointerDeviceType;
            if (pointerDevType == PointerDeviceType.Pen || pointerDevType == PointerDeviceType.Mouse
                && pt.Properties.IsLeftButtonPressed || pointerDevType == PointerDeviceType.Touch)
            {
                _inkManager.ProcessPointerDown(pt);
               
                _penID = pt.PointerId;
                _touchID = pt.PointerId;               
                e.Handled = true;
            }
        }

        private void InkCanvas_PointerMoved(object sender, PointerRoutedEventArgs e)
        {
            if (e.Pointer.PointerId == _penID || e.Pointer.PointerId == _touchID)
            {
                PointerPoint pt = e.GetCurrentPoint(InkCanvas);
                Point currentContactPt = pt.Position;
                if (_CurrentMode != "Erase")
                {
                    Line line = new Line()
                    {
                        X1 = _previousContactPt.X,
                        Y1 = _previousContactPt.Y,
                        X2 = currentContactPt.X,
                        Y2 = currentContactPt.Y,
                        StrokeThickness = _CurrentDrawingSize,
                        Stroke = new SolidColorBrush(_CurrentDrawingColor)
                    };
                    line.Opacity = opacity;
                    _previousContactPt = currentContactPt;
                    InkCanvas.Children.Add(line);
                    
                }
                _inkManager.ProcessPointerUpdate(pt);
                
            }

            e.Handled = true;
        }

        private void InkCanvas_PointerReleased(object sender, PointerRoutedEventArgs e)
        {
            if (e.Pointer.PointerId == _penID || e.Pointer.PointerId == _touchID)
            {
                PointerPoint pt = e.GetCurrentPoint(InkCanvas);
                _inkManager.ProcessPointerUp(pt);
              
            }
            _touchID = 0;
            _penID = 0;
            RefreshCanvas();
            e.Handled = true;
        }

        private void RefreshCanvas()
        {          
            var child = InkCanvas.Children;
            FlipView flipview = new FlipView();
            foreach (var c in child)
            {
                if (c is FlipView)
                    flipview = c as FlipView;
            }
            child.Clear();
            child.Add(flipview);
            RenderStrokes();
        }

        private void RenderStrokes()
        {
            var strokes = _inkManager.GetStrokes();

            foreach (var stroke in strokes)
            {
                RenderStroke(stroke, stroke.DrawingAttributes.Color, stroke.DrawingAttributes.Size.Width, opacity);
            }
        }

        private void RenderStroke(InkStroke stroke, Color color, double width, double opacity)
        {
            var renderingStrokes = stroke.GetRenderingSegments();            
            var path = new Windows.UI.Xaml.Shapes.Path();          
            path.Data = new PathGeometry();           
            ((PathGeometry)path.Data).Figures = new PathFigureCollection();
            var pathFigure = new PathFigure();
            pathFigure.StartPoint = renderingStrokes.First().Position;
            ((PathGeometry)path.Data).Figures.Add(pathFigure);
            foreach (var renderStroke in renderingStrokes)
            {
                pathFigure.Segments.Add(new BezierSegment()
                {
                    Point1 = renderStroke.BezierControlPoint1,
                    Point2 = renderStroke.BezierControlPoint2,
                    Point3 = renderStroke.Position
                });
            }

            path.StrokeThickness = width;
            path.Stroke = new SolidColorBrush(color);
            path.Opacity = opacity;
            InkCanvas.Children.Add(path);
        }

        private void InkMode()
        {
            _CurrentMode = "Ink";
            _inkManager.Mode = Windows.UI.Input.Inking.InkManipulationMode.Inking;
            SetDefaults(_CurrentDrawingSize, _CurrentDrawingColor);

        }
        private void SetDefaults(double strokeSize, Color color)
        {
            var newDrawingAttributes = new InkDrawingAttributes();
            newDrawingAttributes.Size = new Size(strokeSize, strokeSize);
            newDrawingAttributes.Color = color;
            newDrawingAttributes.FitToCurve = true;    
            _inkManager.SetDefaultDrawingAttributes(newDrawingAttributes);
        }
        private void Click_Erase(object sender, RoutedEventArgs e)
        {          
            _inkManager.Mode = Windows.UI.Input.Inking.InkManipulationMode.Erasing;
            var strokes = _inkManager.GetStrokes();
            _inkManager.DeleteSelected();
            _CurrentMode = "Erase";
            Pen.IsEnabled = true;
            Erase.IsEnabled = false;
                 
        }

        private void Click_Clear(object sender, RoutedEventArgs e)
        {
            clear();           
            _CurrentMode = "Ink";
            _inkManager.Mode = Windows.UI.Input.Inking.InkManipulationMode.Inking;          
        }

        private void Click_Pen(object sender, RoutedEventArgs e)
        {          
            Erase.IsEnabled = true;
            Touch.IsEnabled = true;
            Clear.IsEnabled = true;
            Pen.IsEnabled = false;          
            InkCanvas.PointerPressed += new PointerEventHandler(InkCanvas_PointerPressed);
            InkCanvas.PointerMoved += new PointerEventHandler(InkCanvas_PointerMoved);
            InkCanvas.PointerReleased += new PointerEventHandler(InkCanvas_PointerReleased);
            InkCanvas.Visibility = Visibility.Visible;
            InkMode();                    
        }
      
        public void clear()
        {
            _inkManager.Mode = Windows.UI.Input.Inking.InkManipulationMode.Erasing;

            var strokes = _inkManager.GetStrokes();

            for (int i = 0; i < strokes.Count; i++)
            {
                strokes[i].Selected = true;
            }

            _inkManager.DeleteSelected();
            var child = InkCanvas.Children;
            FlipView flipview = new FlipView();
            foreach (var c in child)
            {
                if (c is FlipView)
                    flipview = c as FlipView;
            }
            child.Clear();
            child.Add(flipview);
        }

        private void Click_Touch(object sender, RoutedEventArgs e)
        {
            InkCanvas.PointerPressed -= new PointerEventHandler(InkCanvas_PointerPressed);
            InkCanvas.PointerMoved -= new PointerEventHandler(InkCanvas_PointerMoved);
            InkCanvas.PointerReleased -= new PointerEventHandler(InkCanvas_PointerReleased);
            InkCanvas.Visibility = Visibility.Collapsed;
            clear();
            Pen.IsEnabled = true;
            Touch.IsEnabled = false;
            Erase.IsEnabled = false;
            Clear.IsEnabled = false;
        }
    } 
}
